package com.dongdongshop.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtUtil jwtUtil;

    @Value("#{'${gateway.exclusions.url}'.empty ? null : '${gateway.exclusions.url}'.split(',')}")
    private Set<String> url;

    private PathMatcher pathMatcher = new AntPathMatcher();

    //过滤器功能
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //通过请求取出token, 从请求头取
        ServerHttpRequest request = exchange.getRequest();
        //获取当前的请求路径
        String path = request.getURI().getPath();
        //判断当前路径是否需要验证token
        for (String s : url) {
            if (pathMatcher.match(s, path)){
                return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("AutharizeToken");//传输时token的名字
        if (token == null || "".equals(token)){
            return denyAccess(exchange);
        }
        //如果token存在, 解析token是否合法, 解析不出会抛出异常
        try{
            jwtUtil.parseJwt(token);
        }catch (Exception e){
            return denyAccess(exchange);
        }
        //如果解析成功
        return chain.filter(exchange);
    }

    //如果有多个过滤器, 数字越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 拦截并返回自定义的json字符串
     */
    //封装返回无效的方法
    private Mono<Void> denyAccess(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        //这里在返回头添加编码，否则中文会乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] bytes = JSONObject.toJSONBytes(Result.response(ResultEnum.INVALID_TOKEN), SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }
}
